﻿package com.calefk.modules.sysfx {
	
	import com.calefk.core.EntitySimple;
	import com.calefk.modules.math.Vector2D;
	import com.calefk.util.Generic;
    
    import flash.display.MovieClip;
	
	public class Particle extends EntitySimple {
		
		private var mVelocity:Vector2D;
		private var mAcceleration:Vector2D;
		private var mTimeLife:Number;
		private var mFadeReduce:Number;
		private var mShrink:Number;
		private var mFriction:Number;
		private var mSpinSpeed:Number;
		private var mSpinWithVelocity:Boolean;
		private var mFirstUpdate:Boolean = false;
		
		private var mTotalFrames :int;
		private var mCurrentFrame:int;
		
		public function Particle(canvas:MovieClip, nameClip:String, 
				px:Number, 
				py:Number,
				a:Vector2D,
				v:Vector2D,
				shrink:Number,
				friction:Number,
				fadeReduce:Number,
				timeLife:Number,
				spinSpeed:Number,
				spinWithVelocity:Boolean) {
					
			super(canvas, nameClip, px, py);
			
			mVelocity = v;
			mAcceleration = a;
			mShrink = shrink;
			mFriction = friction;
			mFadeReduce = fadeReduce;
			mTimeLife = timeLife;
			mSpinSpeed = spinSpeed;
			mSpinWithVelocity = spinWithVelocity;
			
			// animation
			mTotalFrames  = mClip.totalFrames;
			mCurrentFrame = 1;
			mClip.gotoAndStop(1);
		}
		
		override public function update(dt:int):void {
			// obliga a que actualice el movimiento al siguiente update
			if (! mFirstUpdate) { mFirstUpdate = true;  return; }
			
			// redutime time left
			mTimeLife -= dt; 
			
			// set position
			move(mVelocity.x , mVelocity.y);
			
			// apply values physic
			mVelocity.scale(mFriction);
			
			mVelocity.add(mAcceleration);
			
			clip.alpha -= mFadeReduce;
			
			// spin
			if (mSpinWithVelocity) {
				clip.rotation = Generic.radToDegrees(mVelocity.getRad());
			} else {
				if (mSpinSpeed != 0) {
					clip.rotation += mSpinSpeed;
				}
			}
			
			// reduce scale
			if (mShrink != 1) {
				clip.scaleX *= mShrink;
				clip.scaleY *= mShrink;
			}
			
			if (mTimeLife <= 0) {
				marketToClean();
			}
			
			if (mCurrentFrame < mTotalFrames) {
				mCurrentFrame++;
				mClip.gotoAndStop(mCurrentFrame);
			}
		}
		
		public function marketToClean():void {
			toClean = true;
		}
		
		override public function clean():void {
			mVelocity = null;
			mAcceleration = null;
			super.clean();
		}
	}
}
